package com.tx.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tx.dao.MajorDao;
import com.tx.dao.impl.MajorDaoImpl;
import com.tx.entity.Major;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/major/*")
public class MajorServlet extends HttpServlet {
    private final MajorDao majorDao = new MajorDaoImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/";
        }

        switch (pathInfo) {
            case "/query":
                handleQuery(request, response);
                break;
            case "/delete":
                handleDelete(request, response);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/";
        }

        switch (pathInfo) {
            case "/query":
                handleQuery(request, response);
                break;
            case "/add":
                handleAdd(request, response);
                break;
            case "/edit":
                handleEdit(request, response);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                break;
        }
    }

    private void handleQuery(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        String name = request.getParameter("name");
        List<Major> majors;
        
        if (name != null && !name.trim().isEmpty()) {
            majors = majorDao.findByName(name);
        } else {
            majors = majorDao.findAll();
        }

        StringBuilder json = new StringBuilder("[");
        for (int i = 0; i < majors.size(); i++) {
            Major major = majors.get(i);
            json.append("{\"id\":").append(major.getId())
                .append(",\"name\":\"").append(major.getName()).append("\"}");
            if (i < majors.size() - 1) {
                json.append(",");
            }
        }
        json.append("]");

        PrintWriter out = response.getWriter();
        out.write(json.toString());
    }

    private void handleAdd(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String name = request.getParameter("name");
            
            if (name == null || name.trim().isEmpty()) {
                throw new IllegalArgumentException("专业名称不能为空");
            }
            
            Major major = new Major(0, name.trim());
            int result = majorDao.add(major);
            
            if (result > 0) {
                out.println("添加成功");
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.println("添加失败");
            }
        } catch (IllegalArgumentException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println("添加失败：" + e.getMessage());
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.println("添加失败：" + e.getMessage());
        }
    }

    private void handleEdit(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String idStr = request.getParameter("id");
            String name = request.getParameter("name");
            
            if (idStr == null || idStr.trim().isEmpty()) {
                throw new IllegalArgumentException("专业ID不能为空");
            }
            if (name == null || name.trim().isEmpty()) {
                throw new IllegalArgumentException("专业名称不能为空");
            }
            
            int id = Integer.parseInt(idStr);
            Major major = new Major(id, name.trim());
            int result = majorDao.update(major);
            
            if (result > 0) {
                out.println("修改成功");
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.println("修改失败");
            }
        } catch (NumberFormatException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println("修改失败：专业ID必须是数字");
        } catch (IllegalArgumentException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println("修改失败：" + e.getMessage());
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.println("修改失败：" + e.getMessage());
        }
    }

    private void handleDelete(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String idStr = request.getParameter("id");
            if (idStr == null || idStr.trim().isEmpty()) {
                throw new IllegalArgumentException("专业ID不能为空");
            }
            
            int id = Integer.parseInt(idStr);
            int result = majorDao.delete(id);
            
            if (result > 0) {
                out.println("删除成功");
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.println("删除失败");
            }
        } catch (NumberFormatException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println("删除失败：专业ID必须是数字");
        } catch (IllegalArgumentException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println("删除失败：" + e.getMessage());
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.println("删除失败：" + e.getMessage());
        }
    }
} 